import axios from 'axios'

const listModules = {
  namespaced: true,
  state: {
    //  所有的任务列表
    list: [],
    //  文本框的内容
    inputValue: 'aaa',
    //  下一个id
    nextId: 5,
    viewKey: 'all'
  },
  getters: {},
  mutations: {
    initList(state, list) {
      state.list = list
    },
    //  为store中的inputValue赋值
    setInputValue(state, val) {
      state.inputValue = val
    },
    //  修改列表项中的选中状态
    changeStatus(state, param) {
      const i = state.list.findIndex((x) => x.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.status
      }
    },
    // 添加列表项
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    // 根据id删除对应的任务事项
    removeItem(state, id) {
      //  根据id查找对应的索引
      const i = state.list.findIndex((x) => x.id === id)
      //  根据索引，删除对应的元素
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    // 清除已完成的任务
    cleanDone(state) {
      state.list = state.list.filter((x) => x.done === false)
    },
    //  修改视图的关键字
    changeViewKey(state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList(context) {
      axios.get('/list.json').then((data) => {
        console.log(data)
        context.commit('initList', data.data)
      })
    }
  }
}

export { listModules as default }
